package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.MessageDAO;
import model.UserDAO;
import beans.MessageBean;
import beans.UserBean;

@WebServlet("/MessagesServlet")
public class MessagesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public MessagesServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{	    
			UserBean user = new UserBean();
			ArrayList<MessageBean> messages = new ArrayList<MessageBean>();
			user.setEmail(request.getParameter("id"));
			String pagenumberstring = request.getParameter("page");
			Integer pagenumber = new Integer(pagenumberstring);
			String box = request.getParameter("box");
			if (pagenumber == 1) {
				if (box.equals("received"))
					messages = MessageDAO.getReceivedMessages(user);
				else if (box.equals("sent"))
					messages = MessageDAO.getSentMessages(user);
			}
			int messagesCount = messages.size();
			HttpSession session = request.getSession(true);
			if (pagenumber == 1)
				session.setAttribute("displaymessages", messages);
			session.setAttribute("currentpagenumber", pagenumber);
			session.setAttribute("currentbox", box);
			session.setAttribute("messagescount", messagesCount);
			response.sendRedirect("messages.jsp"); //logged-in page      		
		} 
		
		catch (Throwable theException) 	    
		{
			System.out.println(theException); 
		}
	}
}
